$(document).ready(function() {
    /**
     * 处理文件显示方式的切换 - 列表和平铺
     */
    $('.wb-gallery-show-type').on('click', function(){
        var $parent = $(this).parent().parent();
        if ($(this).hasClass('fa-th-large')) {
            /* 平铺显示 */
            $parent.find('.wb-listing-gallery').hide();
            $parent.find('.wb-tiled-gallery').show();
            $(this).removeClass('text-muted').addClass('text-primary');
            $(this).parent().find('.fa-th-list').removeClass('text-primary').addClass('text-muted');
        } else {
            /* 列表显示 */
            $parent.find('.wb-tiled-gallery').hide();
            $parent.find('.wb-listing-gallery').show();
            $(this).removeClass('text-muted').addClass('text-primary');
            $(this).parent().find('.fa-th-large').removeClass('text-primary').addClass('text-muted');
        }
    });
    
    /**
     * 新建文件夹
     */
    $('#wb_content').on('click', '.action-mkdir', function(){
        /* 获取参数 */
        var t = $(this).data('type');
        var userid = $('input[name=userid]:last').val();
        
        /* 获取当前文件夹 ID */
        var fid = $('#wb_nav_' + t).find('a:last').data('fid');
        
        /* 执行新建 */
        $.ajax({
            type:'post',
            url:'/attachmentadmin/folderWorkbench/mkdir',
            data:'pid=' + fid + '&userid=' + userid,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    fillTiled(data.data, t, 'before');
                    fillListing(data.data, t, 'before');
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
    
    /**
     * 文件夹重命名 - 切换至输入框
     */
    $('#wb_content').on('click', '.action-rename', function(){
        var obj_item = $(this).parent().parent();
        if ($(this).data('show_type') == 'tiled') {
            obj_item = obj_item.parent();
        }
        obj_item.find('.title').hide();
        obj_item.find('.title-input').show().focus().select();
    });
    
    /**
     * 文件夹重命名 - 执行更新 - 失去焦点方式
     */
    $('#wb_content').on('blur', '.title-input', function(){
        renameFolder($(this).data('folder_id'), $(this).data('show_type'));
    });
    
    /**
     * 文件夹重命名 - 执行更新 - 回车方式
     */
    $('#wb_content').on('keypress', '.title-input', function (event) {
        if (event.which == '13') {
            renameFolder($(this).data('folder_id'), $(this).data('show_type'));
            return false;
        }
    });
    
    /**
     * 删除文件夹
     */
    $('#wb_content').on('click', '.action-delete', function(){
        /* 二次确认 */
        var del = confirm('将连同该文件夹下的内容一并删除。确定要删除该文件夹吗？');
        if (! del) {return false;}
        
        /* 处理参数 */
        var folder_id = $(this).data('folder_id');
        var fid = $(this).data('fid');
        var show_type = $(this).data('show_type');
        var obj_item = $(this).parent().parent();
        if (show_type == 'tiled') {
            obj_item = obj_item.parent();
        }
        var userid = $('input[name=userid]:last').val();
        
        /* 执行删除 */
        $.ajax({
            type:'post',
            url:'/attachmentadmin/folderWorkbench/delete',
            data:'_id=' + folder_id,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    /* 重载统计数字 */
                    var obj_item_top = obj_item.parent();
                    if (show_type == 'listing') {
                        obj_item_top = obj_item_top.parent().parent();
                    }
                    var id_arr = obj_item_top.attr('id').split('_');
                    var wb_type = id_arr[2];
                    if (wb_type == 'video') {
                        wb_type = 'vod';
                    }
                    var obj_count = $('#workbench_' + wb_type).find('font.count-attachment');
                    reloadCount(wb_type, obj_count);

                    /* 清除内容块 */
                    obj_item.remove();
                    
                    /* 同步清除另一种显示模式下的内容块 */
                    var obj_item_other = $('#wb_tiled_item_' + folder_id);
                    if (show_type == 'tiled') {
                        obj_item_other = $('#wb_listing_item_' + folder_id);
                    }
                    obj_item_other.remove();
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
    
    /**
     * 双击打开文件夹
     */
    $('#wb_content').on('dblclick', '.wb-gallery-folder', function(){
        var fid = $(this).data('fid');
        var t = $(this).data('type');
        var obj_nav = $('#wb_nav_' + t);
        var obj_content = $('.wb-gallery-content-' + t);
        var obj_item = $(this).parent().parent();
        var title_old = obj_item.find('.title').text();
        var userid = $('input[name=userid]:last').val();
        
        $.ajax({
            type:'post',
            url:'/attachmentadmin/folderWorkbench/getChildren',
            data:'pid=' + fid + '&t=' + t + '&userid=' + userid,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    /* 清空原有内容 */
                    obj_content.empty();
                    
                    /* 填充新内容 */
                    fillTiled(data.data, t, 'after');
                    fillListing(data.data, t, 'after');
                    
                    /* 处理导航 */
                    if (obj_nav.find('a').size() == 1) {
                        var str_nav = '<a href="javascript:;" data-fid="' + fid + '" data-type="' + t + '">' + title_old + '</a>';
                    } else {
                        var str_nav = '<a href="javascript:;" data-fid="' + fid + '" data-type="' + t + '">&nbsp;/&nbsp;' + title_old + '</a>';
                    }
                    obj_nav.append(str_nav);
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
    
    /**
     * 点击导航返回至某一文件夹
     */
    $('#wb_content').on('click', '.wb-gallery-nav > a', function(){
        var obj_a = $(this);
        var fid = obj_a.data('fid');
        var t = obj_a.data('type');
        var obj_content = $('.wb-gallery-content-' + t);
        var userid = $('input[name=userid]:last').val();
        
        $.ajax({
            type:'post',
            url:'/attachmentadmin/folderWorkbench/getChildren',
            data:'pid=' + fid + '&t=' + t + '&userid=' + userid,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    /* 清空原有内容 */
                    obj_content.empty();
                    
                    /* 填充新内容 */
                    fillTiled(data.data, t, 'after');
                    fillListing(data.data, t, 'after');
                    
                    /* 处理导航 */
                    obj_a.nextAll('a').remove();
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
    
    /**
     * 移动文件 - 显示移动编辑层，并加载可选目录数据
     */
    $('#wb_content').on('click', '.action-move', function(){
        /* 获取参数 */
        var a_id = $(this).data('a_id');
        var folder_hid = $(this).data('folder_hid');
        var t = $(this).data('type');
        var obj_modal = $('#modal_wb_move_attachment');
        var userid = $('input[name=userid]:last').val();
        
        /* 加载可选目录数据 */
        $.ajax({
            type:'post',
            url:'/attachmentadmin/folderWorkbench/getFoldersForSelect',
            data:'folder_hid=' + folder_hid + '&userid=' + userid,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    /* 渲染数据 */
                    var options = '';
                    $(data.data.folders_forselect).each(function(k, v){
                        options += '<option value="' + v.fid + '">' + v.str_padding + v.title + '</option>';
                    });
                    obj_modal.find('select').empty().append(options);
                    
                    /* 显示层 */
                    obj_modal.find('.input-submit-move').data('type', t);
                    obj_modal.find('input[name=a_id]:last').val(a_id);
                    obj_modal.modal('show');
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
    
    /**
     * 移动文件 - 提交
     */
    $('#modal_wb_move_attachment').on('click', '.input-submit-move', function(){
        /* 获取参数 */
        var t = $(this).data('type');
        var obj_modal = $('#modal_wb_move_attachment');
        var fid = obj_modal.find('select').val();
        var a_id = obj_modal.find('input[name=a_id]:last').val();
        var userid = $('input[name=userid]:last').val();
        
        /* 执行提交 */
        $.ajax({
            type:'post',
            url:'/attachmentadmin/content/move',
            data:'a_id=' + a_id + '&fid=' + fid + '&userid=' + userid,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    /* 清除文件块内容 */
                    $('#wb_listing_item_' + a_id).remove();
                    $('#wb_tiled_item_' + a_id).remove();
                    obj_modal.modal('hide');
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
});


/**
 * 文件夹重命名 - 执行更新
 * 
 * @param string folder_id 文件夹 ID
 * @param string show_type 展示类型。平铺 or 列表
 * @return boolean
 */
function renameFolder(folder_id, show_type) {
    /* 获取参数 */
    var obj_item = $('#wb_' + show_type + '_item_' + folder_id);
    var title_new = obj_item.find('.title-input').val();
    var title_old = obj_item.find('.title').text();
    var userid = $('input[name=userid]:last').val();
    
    /* 校验必填项 */
    if (! title_new) {
        alert('文件夹名称不能为空');
        return false;
    }
    
    if (title_new == title_old) {
        /* 没有发生变化，直接切换显示方式 */
        obj_item.find('.title-input').hide();
        obj_item.find('.title').show();
    } else {
        /* 发生了变化，执行更新 */
        $.ajax({
            type:'post',
            url:'/attachmentadmin/folderWorkbench/rename',
            data:'folder_id=' + folder_id + '&title=' + title_new + '&userid=' + userid,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    /* 更新显示内容，并切换显示方式 */
                    obj_item.find('.title-input').hide();
                    obj_item.find('.title').text(title_new).show();
                    
                    /* 同步至另外一种显示模式下 */
                    var obj_item_other = $('#wb_tiled_item_' + folder_id);
                    if (show_type == 'tiled') {
                        obj_item_other = $('#wb_listing_item_' + folder_id);
                    }
                    obj_item_other.find('.title').text(title_new);
                    obj_item_other.find('.title-input').val(title_new);
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    }
}

/**
 * 填充新的文件(夹)信息 - 平铺模式
 * 
 * @param obj d 数据
 * @param string t 文件类型：image、audio、vod
 * @param string s 文件夹插入位置。before：往前插入；after：往后插入；
 */
function fillTiled(d, t, s) {
    /* 处理编辑 url 地址中的类型 */
    var t_url = t == 'video' ? 'vod' : t;
    
    /* 定义目录模板 */
    var t_folder = '<div class="item" id="wb_tiled_item_{#folder_id#}">' + 
            '<div class="text-center tiled-item-top">' + 
            '<i class="fa fa-folder-open cursor-pointer m-t wb-gallery-folder" data-fid="{#fid#}" data-type="' + t + '"></i>' + 
            '</div>' + 
            '<div class="tiled-item-bottom">' + 
            '<div class="text-center padder-t-xs padder-b-xs tiled-info">' + 
            '<font class="title">{#title#}</font>' + 
            '<input type="text" class="form-control title-input default-hidden" value="{#title#}" data-folder_id="{#folder_id#}" data-show_type="tiled" />' + 
            '</div>' + 
            '<div class="btn-group btn-group-justified">' + 
            '<a class="btn btn-sm btn-orange action-rename" data-show_type="tiled">重命名</a>' + 
            '<a class="btn btn-sm btn-red action-delete" data-folder_id="{#folder_id#}" data-fid="{#fid#}" data-show_type="tiled">删除</a>' + 
            '</div></div></div>';
    
    /* 定义文件模板 */
    var t_content = '<div class="item" id="wb_tiled_item_{#a_id#}">';
    if (t == 'image') {
        t_content += '<div class="tiled-item-top">' + 
                '<a href="/workbenchadmin/' + t_url + '?_id={#pid#}&card_id={#card_id#}" title="点击进入编辑" target="_blank">' + 
                '<img src="/uploads{#filepath#}" width="142" height="90" />' + 
                '</a>' + 
                '</div>';
    } else if (t == 'audio') {
        t_content += '<div class="text-center tiled-item-top">' + 
                '<a href="/workbenchadmin/' + t_url + '?_id={#pid#}&card_id={#card_id#}" title="点击进入编辑" target="_blank">' + 
                '<i class="fa fa-music m-t wb-gallery-folder"></i>' + 
                '</a>' + 
                '</div>';
    } else if (t == 'video') {
        t_content += '<div class="text-center tiled-item-top">' + 
                '<a href="/workbenchadmin/' + t_url + '?_id={#pid#}&card_id={#card_id#}" title="点击进入编辑" target="_blank">' + 
                '{#video_cover#}' + 
                '</a>' + 
                '</div>';
    }
    t_content += '<div class="tiled-item-bottom">' + 
            '<div class="text-center padder-t-xs padder-b-xs tiled-info">{#title#}.{#suffix#}</div>' + 
            '<div class="btn-group btn-group-justified">' + 
            '<a class="btn btn-sm btn-orange" href="/workbenchadmin/' + t_url + '?_id={#pid#}&card_id={#card_id#}" target="_blank">编辑</a>' + 
            '<a class="btn btn-sm btn-info action-move" data-a_id="{#a_id#}" data-folder_hid="{#folder_hid#}" data-type="' + t + '">移动</a>' + 
            '<a class="btn btn-sm btn-lightblue" href="' + DOWNLOAD_URL + '?_id={#a_id#}" target="_blank">下载</a>' + 
            '</div></div></div>';
    
    /* 处理目录 */
    if (d.folder_info) {
        $(d.folder_info).each(function(k, v){
            /* 处理模板 */
            var str_folder = t_folder.replace(/{#folder_id#}/g, v._id);
            str_folder = str_folder.replace(/{#fid#}/g, v.fid);
            str_folder = str_folder.replace(/{#title#}/g, v.title);
            
            if (s == 'before') {
                $('#wb_tiled_' + t + '_content').prepend(str_folder);
            } else {
                $('#wb_tiled_' + t + '_content').append(str_folder);
            }
        });
    }
    
    /* 处理文件 */
    if (d.content_info) {
        $(d.content_info).each(function(k, v){
            /* 处理模板 */
            var str_content = t_content.replace(/{#a_id#}/g, v._id);
            str_content = str_content.replace(/{#pid#}/g, v.pid);
            str_content = str_content.replace(/{#card_id#}/g, v.card_id);
            str_content = str_content.replace(/{#filepath#}/g, v.filepath);
            str_content = str_content.replace(/{#title#}/g, v.title);
            str_content = str_content.replace(/{#suffix#}/g, v.suffix);
            str_content = str_content.replace(/{#folder_hid#}/g, d.folder_info_parent.hid);
            
            /* 处理视频封面 */
            if (v.mediatype == 'video') {
                var str_cover = '<i class="fa fa-film m-t wb-gallery-folder"></i>';
                if (v.extra.cover) {
                    str_cover = '<img src="/uploads' + v.extra.cover + '" width="142" height="90" />';
                }
                str_content = str_content.replace(/{#video_cover#}/g, str_cover);
            }
            
            $('#wb_tiled_' + t + '_content').append(str_content);
        });
    }
}

/**
 * 填充新的文件(夹)信息 - 列表模式
 * 
 * @param obj d 数据
 * @param string t 文件类型：image、audio、vod
 * @param string s 文件夹插入位置。before：往前插入；after：往后插入；
 */
function fillListing(d, t, s) {
    /* 处理编辑 url 地址中的类型 */
    var t_url = t == 'video' ? 'vod' : t;
    
    /* 定义目录模板 */
    var t_folder = '<tr id="wb_listing_item_{#folder_id#}">';
    if (t == 'image') {
        t_folder += '<td class="v-middle">-</td>';
    }
    t_folder += '<td class="v-middle">' + 
            '<i class="fa fa-folder-open cursor-pointer m-t wb-gallery-folder" data-fid="{#fid#}" data-type="' + t + '"></i>' + 
            '</td>' + 
            '<td class="v-middle">' + 
            '<font class="title">{#title#}</font>' + 
            '<input type="text" class="form-control title-input default-hidden" value="{#title#}" data-folder_id="{#folder_id#}" data-show_type="listing" />' + 
            '</td>' + 
            '<td class="v-middle">-</td>' + 
            '<td class="v-middle">-</td>' + 
            '<td class="v-middle">-</td>' + 
            '<td class="v-middle">-</td>' + 
            '<td class="v-middle">{#ctime#}</td>' + 
            '<td class="v-middle">' + 
            '<a class="btn btn-xs btn-orange action-rename" data-show_type="listing">' + 
            '<i class="fa fa-pencil"></i><span> 重命名</span>' + 
            '</a>&nbsp;' + 
            '<a class="btn btn-xs btn-red action-delete" data-folder_id="{#folder_id#}" data-fid="{#fid#}" data-show_type="listing">' + 
            '<i class="fa fa-trash-o"></i><span> 删除</span>' + 
            '</a>' + 
            '</td>' + 
            '</tr>';
    
    /* 定义文件模板 */
    var t_content = '<tr id="wb_listing_item_{#a_id#}">';
    if (t == 'image') {
        t_content += '<td><input type="checkbox" name="post[]" class="checkbox-print" value="{#a_id#}"></td>' + 
                '<td class="v-middle">' + 
                '<a href="/workbenchadmin/image?_id={#pid#}&card_id={#card_id#}" title="点击进入编辑" target="_blank">' + 
                '<img src="/uploads{#filepath#}" class="thumb-lg" border="0" />' + 
                '</a>' + 
                '</td>';
    } else if (t == 'audio') {
        t_content += '<td class="v-middle">' + 
                '<a href="/workbenchadmin/audio?_id={#pid#}&card_id={#card_id#}" title="点击进入编辑" target="_blank">' + 
                '<i class="fa fa-music text-xxxl"></i>' + 
                '</a>' + 
                '</td>';
    } else if (t == 'video') {
        t_content += '<td class="v-middle">' + 
                '<a href="/workbenchadmin/vod?_id={#pid#}&card_id={#card_id#}" title="点击进入编辑" target="_blank">' + 
                '{#video_cover#}' + 
                '</a>' + 
                '</td>';
    }
    t_content += '<td class="v-middle">{#title_from#}</td>';
    if (t == 'audio' || t == 'video') {
        t_content += '<td class="v-middle">{#duration#} 秒</td>';
    } else if (t == 'image') {
        t_content += '<td class="v-middle">{#image_width#} x {#image_height#} px</td>';
    }
    t_content += '<td class="v-middle">{#filesize#}</td>' + 
            '<td class="v-middle">{#card_title#}</td>' + 
            '<td class="v-middle">{#archive_title#}</td>' + 
            '<td class="v-middle">{#ctime#}</td>' + 
            '<td class="v-middle">' + 
            '<a href="/workbenchadmin/' + t_url + '?_id={#pid#}&card_id={#card_id#}" class="btn btn-xs btn-orange edit-single" target="_blank">' + 
            '<i class="fa fa-pencil"></i><span> 编辑</span>' + 
            '</a>&nbsp;' + 
            '<a class="btn btn-xs btn-info action-move" data-card_id="{#card_id#}" data-a_id="{#a_id#}" data-folder_hid="{#folder_hid#}" data-type="' + t + '">' + 
            '<i class="fa fa-pencil"></i><span>移动' + 
            '</a>&nbsp;' + 
            '<a href="' + DOWNLOAD_URL + '?_id={#a_id#}" class="btn btn-xs btn-lightblue" target="_blank">' + 
            '<i class="fa fa-download"></i><span> 下载</span>' + 
            '</a>' + 
            '</td>' + 
            '</tr>';
    
    /* 处理目录 */
    if (d.folder_info) {
        $(d.folder_info).each(function(k, v){
            /* 处理模板 */
            var str_folder = t_folder.replace(/{#folder_id#}/g, v._id);
            str_folder = str_folder.replace(/{#fid#}/g, v.fid);
            str_folder = str_folder.replace(/{#title#}/g, v.title);
            str_folder = str_folder.replace(/{#ctime#}/g, v.ctime);
            
            if (s == 'before') {
                $('#wb_listing_' + t + '_content').find('tbody').prepend(str_folder);
            } else {
                $('#wb_listing_' + t + '_content').find('tbody').append(str_folder);
            }
        });
    }
    
    /* 处理文件 */
    if (d.content_info) {
        $(d.content_info).each(function(k, v){
            /* 处理模板 */
            var str_content = t_content.replace(/{#a_id#}/g, v._id);
            str_content = str_content.replace(/{#pid#}/g, v.pid);
            str_content = str_content.replace(/{#card_id#}/g, v.card_id);
            str_content = str_content.replace(/{#filepath#}/g, v.filepath);
            str_content = str_content.replace(/{#title_from#}/g, v.title_from);
            str_content = str_content.replace(/{#duration#}/g, v.extra.duration);
            str_content = str_content.replace(/{#image_width#}/g, v.image_width);
            str_content = str_content.replace(/{#image_height#}/g, v.image_height);
            str_content = str_content.replace(/{#filesize#}/g, v.filesize_format);
            str_content = str_content.replace(/{#card_title#}/g, v.card_title);
            str_content = str_content.replace(/{#archive_title#}/g, v.archive_title);
            str_content = str_content.replace(/{#ctime#}/g, v.ctime);
            str_content = str_content.replace(/{#folder_hid#}/g, d.folder_info_parent.hid);
            
            /* 处理视频封面 */
            if (v.mediatype == 'video') {
                var str_cover = '<i class="fa fa-film text-xxxl"></i>';
                if (v.extra.cover) {
                    str_cover = '<img src="/uploads' + v.extra.cover + '" class="thumb-lg" border="0" />';
                }
                str_content = str_content.replace(/{#video_cover#}/g, str_cover);
            }
            
            $('#wb_listing_' + t + '_content').find('tbody').append(str_content);
        });
    }
}

/**
 * 重载统计数字
 *
 * @param string t 统计文件类型：video、audio、image
 * @param object obj_count 统计数字容器
 */
function reloadCount(t, obj_count) {
    /* 处理类型 */
    if (t == 'vod') {
        t = 'video';
    }

    /* 执行查询 */
    $.ajax({
        type:'post',
        url:'/index/getWbCount',
        data:'type=' + t,
        dataType:'json',
        timeout:60000,
        success:function(data){
            if (data.status == 0) {
                /* 更新显示内容，并切换显示方式 */
                obj_count.text(data.data.count);
            } else {
                alert(data.error);
            }
            return false;
        }
    });
}
